package civicinity.ist.psu.edu.events;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.adapter.CivicinityImageLoader;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.utils.CivicinityCameraMode;
import civicinity.ist.psu.edu.utils.CivicinityDrawableManager;
import civicinity.ist.psu.edu.utils.DownloadHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class CivicinityGallery extends Activity {

    private int mEventID = 0;
    private String mSelectedImagePath;
    private ArrayList<String> mArr = new ArrayList<String>();
    
    private Gallery mGallery;
    private ProgressBar mSpinner;
    private TextView mLoadingTxt;
    private TextView mNoPhotoTxt;
    private TextView mNumPhotoTxt;
    private ImageView imageView;
    private ImageView mNoPhotoYetView;
    private Button participateBtn;
    private Button participateBtn2;
    
    private static final int SELECT_PICTURE = 1;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.civicinity_gallery);
        
        mGallery = (Gallery)findViewById(R.id.Gallery01);
        mSpinner = (ProgressBar)findViewById(R.id.spinner);
        mLoadingTxt = (TextView)findViewById(R.id.loading_text);
        mNoPhotoTxt = (TextView)findViewById(R.id.click_photo);
        mNumPhotoTxt = (TextView)findViewById(R.id.num_photo);
        participateBtn = (Button)findViewById(R.id.upload);
        participateBtn2 = (Button)findViewById(R.id.take_photo_btn);
        
        
        Intent gIntent = getIntent();
        mEventID = gIntent.getExtras().getInt("event_id");
        
        imageView = (ImageView)findViewById(R.id.ImageView01);
        mNoPhotoYetView = (ImageView)findViewById(R.id.no_photo_yet);
        
        new downloadEventPhoto().execute();
        
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	
    	mGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				
				mNoPhotoTxt.setVisibility(View.GONE);
				
				mNumPhotoTxt.setVisibility(View.VISIBLE);
				mNumPhotoTxt.setText(position + 1 + " / " + mArr.size());
				
				ProgressBar spinner = (ProgressBar)findViewById(R.id.spinner);
				TextView textView = (TextView)findViewById(R.id.loading_text);
				textView.setText("Loading image...");
				textView.setVisibility(View.VISIBLE);
				
				CivicinityDrawableManager dm = new CivicinityDrawableManager(CivicinityGallery.this, spinner, imageView);
				dm.fetchDrawableOnThread(Constants.DOWNLOAD_SHARE_IMAGE + mArr.get(position));
			}
        });

    }
    
    private class downloadEventPhoto extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			DownloadHandler dHandler = new DownloadHandler();
			String getResponse = dHandler.downloadJson(Constants.DOWNLOAD_EVENT_PHOTO_INFO + "?event_id=" + mEventID);
			
			Log.i("K", "Event request URL : " + Constants.DOWNLOAD_EVENT_PHOTO_INFO + "?event_id=" + mEventID);

			try{
				JSONObject jObj = new JSONObject(getResponse);
				
				if(jObj.getBoolean("success")) {
					JSONArray jsonAry = new JSONArray(jObj.getString("results"));
					
					for(int i = 0; i < jsonAry.length(); i++){
				
						mArr.add(jsonAry.getJSONObject(i).getString("image"));
					
					}
					Log.d("K", "download event info.");
				}
				
				//mDB.setShareOthers(mShareOthersArr);
				
			} catch(Exception e){}
			
			
			return null;
		}
		
		@Override
	  	protected void onPostExecute(Void unused) {
			
			
			Log.i("K", "mArr size : " + mArr.size());
			mSpinner.setVisibility(View.GONE);
			mLoadingTxt.setVisibility(View.GONE);
			
			if(mArr.size() == 0) {
				// since there is no photo in the selected event,
				// show the textview to explain about this,
				// and encourage users to participate the event by showing the bottom which leads users to 
				// participate.
				mNoPhotoTxt.setText("No photos are available in this event.\nBe the first person on this event!");
				mNoPhotoTxt.setVisibility(View.VISIBLE);
				participateBtn.setVisibility(View.VISIBLE);
				mNoPhotoYetView.setVisibility(View.VISIBLE);
				mNoPhotoYetView.setImageResource(R.drawable.camera_icon);
				
				participateBtn.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						final CharSequence[] choiceSeq = {"Choose from Gallery", "Capture a photo"};
						
						new AlertDialog.Builder(CivicinityGallery.this)
				   		.setTitle("Upload photo")
				   		.setItems(choiceSeq, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								if(which == 0) {
									Intent intent = new Intent();
				                    intent.setType("image/*");
				                    intent.setAction(Intent.ACTION_GET_CONTENT);
				                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
								}
								else {
									Intent intent = new Intent(CivicinityGallery.this, CivicinityCameraMode.class);
									intent.putExtra("prev_activity", Constants.PREV_ACITIVITY_EVENT);
									intent.putExtra("event_id", mEventID);
									startActivity(intent);
								}
							}
						})
				   		.show();
					}
				});
			}
			else {
				//show the first photo.
				ProgressBar spinner = (ProgressBar)findViewById(R.id.spinner);
				TextView textView = (TextView)findViewById(R.id.loading_text);
				textView.setText("Loading image...");
				textView.setVisibility(View.VISIBLE);
				
				CivicinityDrawableManager dm = new CivicinityDrawableManager(CivicinityGallery.this, spinner, imageView);
				dm.fetchDrawableOnThread(Constants.DOWNLOAD_SHARE_IMAGE + mArr.get(0));
				
				mNumPhotoTxt.setVisibility(View.VISIBLE);
				mNumPhotoTxt.setText("1 / " + mArr.size());
				
				participateBtn2.setVisibility(View.VISIBLE);
				participateBtn2.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						final CharSequence[] choiceSeq = {"Choose from Gallery", "Capture a photo"};
						
						new AlertDialog.Builder(CivicinityGallery.this)
				   		.setTitle("Upload photo")
				   		.setItems(choiceSeq, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								if(which == 0) {
									Intent intent = new Intent();
				                    intent.setType("image/*");
				                    intent.setAction(Intent.ACTION_GET_CONTENT);
				                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
								}
								else {
									Intent intent = new Intent(CivicinityGallery.this, CivicinityCameraMode.class);
									intent.putExtra("prev_activity", Constants.PREV_ACITIVITY_EVENT);
									intent.putExtra("event_id", mEventID);
									startActivity(intent);
								}
							}
						})
				   		.show();
					}
				});
				
				//mNoPhotoTxt.setText(mArr.size() + " photos. Click a photo at the top.");
				//mNoPhotoTxt.setVisibility(View.VISIBLE);
			}
		
			ImageAdapter adapter = new ImageAdapter(CivicinityGallery.this);
			mGallery.setAdapter(adapter);
		}
    }
    
    /**
     * The class for holding thumbnail images in the event.
     * Gallery view is also composed of the adapter, therefore, the way how to use this widget
     * is straightforward.
     * @author kyunghan
     *
     */
    public class ImageAdapter extends BaseAdapter {

    	private Context mContext;
    	private int imageBackground;
    	public CivicinityImageLoader imageLoader;
    	private LayoutInflater inflater = null;
    	
    	public ImageAdapter(Context context) {
    		mContext = context;
			
    		TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
			imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
			ta.recycle();
			
			inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			imageLoader = new CivicinityImageLoader(mContext.getApplicationContext());
		}

		@Override
    	public int getCount() {
    		return mArr.size();
    	}

    	@Override
    	public Object getItem(int position) {
    		return position;
    	}

    	@Override
    	public long getItemId(int position) {
    		return position;
    	}

    	public class ViewHolder{
    		public ImageView thumbnail;
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		
    		View vi=convertView;
            ViewHolder holder;
            if(convertView == null){
                vi = inflater.inflate(R.layout.event_photo_item, null);
                holder = new ViewHolder();
                holder.thumbnail = (ImageView)vi.findViewById(R.id.event_image);
                vi.setTag(holder);
            }
            else
                holder = (ViewHolder)vi.getTag();
    		
            // for image
            holder.thumbnail.setTag(Constants.DOWNLOAD_SHARE_THUMBNAIL + mArr.get(position));
            holder.thumbnail.setScaleType(ImageView.ScaleType.FIT_XY);
            //holder.thumbnail.setLayoutParams(new Gallery.LayoutParams(150,120));
            //holder.thumbnail.setBackgroundResource(imageBackground);
            imageLoader.DisplayImage(Constants.DOWNLOAD_SHARE_THUMBNAIL + mArr.get(position), mContext, holder.thumbnail);
            
    		return vi;
    	}
    }
    
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            mSelectedImagePath = getPath(selectedImageUri);
	            
	            Intent intent = new Intent(this, CivicinityEventParticipate.class);
	            intent.putExtra("image_path", mSelectedImagePath);
	            intent.putExtra("event_id", mEventID);
	            startActivity(intent);
	            
	            finish();
	        }
	    }
	}
	
	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
}